//
// Created by LiuYou on 2021/7/24.
//

#include "Message.hpp"

#include <utility>

Demo::Message::Message(std::string contents) : contents( std::move( contents )) {}

Demo::Message::~Message() {
    removeFromFolders();

}

Demo::Message& Demo::Message::operator=(const Demo::Message& rhs) {
    removeFromFolders();
    contents = rhs.contents;
    folders = rhs.folders;
    addToFolders( rhs );
    return *this;
}

void Demo::Message::save(Demo::Folder& folder) {
    folders.insert( &folder );
    folder.addMsg( this );
}

void Demo::Message::remove(Demo::Folder& folder) {
    folders.erase( &folder );
    folder.removeMsg( this );
}

void Demo::Message::addToFolders(const Demo::Message& message) {
    for (auto& item : message.folders) {
        item.addMsg( this );
    }

}

void Demo::Message::removeFromFolders() {
    for (auto& item : folders) {
        item.removeMsg( this );
    }

}

Demo::Message::Message(const Demo::Message& rhs) :
        contents( rhs.contents ), folders( rhs.folders ) {
    addToFolders( rhs );
}

void Demo::swap(Demo::Message& lhs, Demo::Message& rhs) {
    for (auto& item : lhs.folders) {
        item.removeMsg( &lhs );
    }
    for (auto& item : rhs.folders) {
        item.removeMsg( &rhs );
    }
    std::swap( lhs.folders, rhs.folders );
    std::swap( lhs.contents, rhs.contents );
    for (auto& item : lhs.folders) {
        item.addMsg( &lhs );
    }
    for (auto& item : rhs.folders) {
        item.addMsg( &rhs );
    }

}
